import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Tooltip, Spin } from 'antd';
import {
  WeaTop,
  WeaRightMenu,
  WeaLocaleProvider,
  WeaLeftRightLayout,
  WeaPopoverHrm,
} from 'ecCom';
import { WeaLogView } from 'comsMobx';

const getLabel = WeaLocaleProvider.getLabel;
import CoworkConstant from '../../util/CoworkConstant';
import CoworkTree from './CoworkTree';
import CoworkField from './CoworkField';
import CoworkTable from './CoworkTable';
import CoworkTagDialog from './dialog/CoworkTagDialog';
import NewCowork from './dialog/NewCowork';

const WeaLogViewComp = WeaLogView.Component;
const storeMapKey = 1; // 当前页面获取 新建协作的store 的key
const coworkEnginePlateKey = 3;
const coworkEngineCategoryKey = 2;

const COMP = ({ children, func, type, ...rest }) => {
  const onHandleClick = e => func(e, type);
  return (
    <span {...rest} onClick={onHandleClick}>
      {children}
    </span>
  );
};

const store = ['coworkMainStore', 'coworkStoreMap'];
@inject(...store)
@observer
class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      type: 'field',
      showLog: false,
      targetId: '',
    };
  }

  componentDidMount() {
    // 处理门户进入协作交流传入name，更新左侧
    const { query = {} } = this.props.location;
    /* const {name = '',jointype = '',status = '',typeid = '',viewType=''} = query;
     if (name !== '') {
       this.props.coworkMainStore.doInit(() => {
         const {form} = this.props.coworkMainStore.leftList;
         form && form.updateFields({name: name});
       });
     }else if(jointype !== ''&&status !== ''&&typeid !== ''&&viewType !== ''){//门户more必定传这四个传值（主要为了匹配门户more打开后匹配参数查询）
       this.props.coworkMainStore.doInit(() => {
         const {form} = this.props.coworkMainStore.leftList;
         form && form.updateFields({jointype: jointype,status: status,typeid: typeid, viewType: viewType});
       });
     }
    */

    // 支持随意参数组合拼接
    if (JSON.stringify(query) !== '{}') {
      this.props.coworkMainStore.doInit(() => {
        const { form } = this.props.coworkMainStore.leftList;
        let queryParams = {};
        Object.keys(query).forEach((item) => {
          queryParams = {
            ...queryParams,
            [item]: { value: query[item] },
          };
        });
        form && form.updateFields(queryParams);
        if (query.jointype) {
          this.props.coworkMainStore.setStoreState({
            formJoinType: query.jointype,
          });
        }
      });
    } else {
      this.props.coworkMainStore.doInit();
    }
    // 异步加载后端协作模块
    if (!window.weaCoworkEngine) {
      // 异步加载别模块的静态资源
      eventRegister.loadModule(
        'b_cowork',
        () => {
          this.props.coworkMainStore.setLoaded(true);
        },
        () => {
          // 加载文件失败 的业务处理， 网络超时，没文件之类
        },
      );
    } else {
      this.props.coworkMainStore.setLoaded(true);
    }
  }

  componentWillReceiveProps(nextProps) {
    // fix:菜单切换报错
    if (
      this.props.location.key !== nextProps.location.key &&
      !this.props.coworkMainStore.initing
    ) {
      this.setState({ type: 'field' });
    }

    // 处理门户进入协作交流传入name，更新左侧
    const firstName =
      this.props.location &&
      this.props.location.query &&
      this.props.location.query.name;
    const nextName =
      nextProps.location &&
      nextProps.location.query &&
      nextProps.location.query.name;
    if (
      nextProps.params &&
      (nextProps.params.coworkId || nextProps.params.floorNum)
    ) {
      // 只是内部的id变化，不需要初始化操作 -- 必须加的判断，这里key也会变化，但是不需要初始化
      if (
        this.props.location.key !== nextProps.location.key &&
        this.props.params.coworkId == nextProps.params.coworkId
      ) {
        // fix:连续点击同一个协作主题，也可以刷新
        const { coworkMainStore } = this.props;
        coworkMainStore.chooseCowork(
          nextProps.params.coworkId,
          nextProps.params.floorNum,
        ); // 走接口
        coworkMainStore.initDetailParams(); // 协作详情 参数初始化
        coworkMainStore.content.searchForm &&
          coworkMainStore.content.searchForm.resetConditionValue(); // form重置
      } else {
      }
    } else if (nextName && nextName !== firstName) {
      // 门户传入name的初始化
      this.props.coworkMainStore.doInit(() => {
        const { form } = this.props.coworkMainStore.leftList;
        form && form.updateFields({ name: nextName });
      });
    } else if (
      this.props.location.key !== nextProps.location.key &&
      !this.props.coworkMainStore.initing
    ) {
      // 菜单切换的初始化
      this.props.coworkMainStore.doInit();
    }
  }

  componentWillUnmount() {
    this.props.coworkMainStore.clearParams(); // 卸载的时候 左侧数据需要回到初始化状态
  }

  setTag = () => {
    const { setTagVisible, getCoworkLabelList } = this.props.coworkMainStore;
    getCoworkLabelList();
    setTagVisible(true);
  };

  onDropMenuClick = (key) => {
    if (key == 'add') {
      // 新建协作
      const coworkNewStore = this.props.coworkStoreMap.getMapStore(storeMapKey);
      coworkNewStore.setCreateState({ showNewCowork: true, createOrEdit: 0 });
      coworkNewStore.setStoreState({ topTitle: getLabel(18034, '新建协作') });
      // 实时取版块下拉框数据
      coworkNewStore.getNewMyCoworkTypeList();
      coworkNewStore.coworkAddCondition();
    } else if (key == 'type') {
      // 版块设置
      if (window.weaCoworkEngine) {
        const coworkEngineStoreMap =
          window.weaCoworkEngine &&
          window.weaCoworkEngine.store.coworkEngineStoreMap;
        const coworkPlateSetStore =
          coworkEngineStoreMap &&
          coworkEngineStoreMap.getPlateSetStore(coworkEnginePlateKey);
        coworkPlateSetStore &&
          coworkPlateSetStore.getCoworkTypeList(true, true); // 第二个true会直接展示dialog
        // coworkPlateSetStore && coworkPlateSetStore.setDialogVisible(true);
        coworkPlateSetStore && coworkPlateSetStore.getCoworkMainTypeComboList(); // 新建版块，获取协作类别下拉框
      }
    } else if (key == 'log') {
      // 日志
      this.setState({ showLog: true });
    } else if (window.weaCoworkEngine) {
      // 类别设置
      const coworkEngineStoreMap =
        window.weaCoworkEngine &&
        window.weaCoworkEngine.store.coworkEngineStoreMap;
      const coworkCategorySetStore =
        coworkEngineStoreMap &&
        coworkEngineStoreMap.getCategorySetStore(coworkEngineCategoryKey);
      coworkCategorySetStore &&
        coworkCategorySetStore.getCoworkMainTypeList(true, true); // 第二个true会直接展示dialog
      // coworkCategorySetStore && coworkCategorySetStore.setDialogVisible(true);
    }
  };

  changeType = (e, type) => {
    e.preventDefault();
    e.stopPropagation();
    this.setState({ type });
    const {
      reloadLeftList,
      setParams,
      coworkChangeView,
    } = this.props.coworkMainStore;
    setParams({ layout: type == 'field' ? 1 : 2 });
    coworkChangeView({ layout: type == 'field' ? '1' : '2' });
    reloadLeftList();
  };

  getDropList = (authority) => {
    let dropMenuList = [
      {
        key: 'add',
        icon: <span className="icon-coms-New-Flow" />,
        content: getLabel(18034, '新建协作'),
      },
    ];
    if (authority.type == 1) {
      dropMenuList.push({
        key: 'type',
        icon: <span className="icon-coms-plate" />,
        content: getLabel(33690, '版块设置'),
        disabled: !(
          this.props.coworkMainStore.loaded && window.weaCoworkEngine
        ),
      });
    }
    if (authority.mainType == 1) {
      dropMenuList.push({
        key: 'mainType',
        icon: <span className="icon-coms-Journal" />,
        content: getLabel(16493, '类别设置'),
        disabled: !(
          this.props.coworkMainStore.loaded && window.weaCoworkEngine
        ),
      });
    }
    if (authority.userid == 1) {
      dropMenuList.push({
        key: 'log',
        icon: <span className="icon-coms-Print-log" />,
        content: getLabel(83, '日志'),
      });
    }
    return dropMenuList;
  };
  onLogViewCancel = () => this.setState({ showLog: false });

  onAddCowork = () => this.onDropMenuClick('add');

  render() {
    const { coworkMainStore } = this.props;
    const { logStore, logstatus, leftList } = coworkMainStore;
    const { logType, logSmallType } = logstatus;
    let /* {type} = this.state, */ config = coworkMainStore.config,
      { authority } = config;
    let loading = false;
    let type = leftList.params.layout * 1 === 1 ? 'field' : 'list';
    if (type == 'field') {
      loading = coworkMainStore.leftList.loading;
      loading =
        loading ||
        (coworkMainStore.content.id && coworkMainStore.content.loading);
    } else {
      loading = coworkMainStore.comsWeaTableStore.loading;
    }
    const dropList = this.getDropList(authority) || [];
    const CoworkEngine =
      (window.weaCoworkEngine && window.weaCoworkEngine.com) || null;
    const PlateSetDialog =
      (CoworkEngine && CoworkEngine.PlateSetDialog) || React.Fragment;
    const CategorySetDialog =
      (CoworkEngine && CoworkEngine.CategorySetDialog) || React.Fragment;
    return (
      <div className="wea-cowork-main">
        <WeaPopoverHrm
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaPopoverHrm@30ytcx`}
        />
        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@8zhmdm`}
          datas={dropList}
          onClick={this.onDropMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@vchu7h`}
            title={getLabel(32571, '协作交流')}
            icon={CoworkConstant.icon}
            iconBgcolor={CoworkConstant.iconBgColor}
            loading={loading}
            buttons={[
              <Button
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Button@i1b93a@add`}
                type="primary"
                onClick={this.onAddCowork}
              >
                {getLabel(18034, '新建协作')}
              </Button>,
              <Button
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Button@ffeupf@setTag`}
                type="primary"
                onClick={this.setTag}
              >
                {getLabel(30884, '标签设置')}
              </Button>,
              <span className="view-change">
                <Tooltip
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Tooltip@9orokt@${type}`}
                  title={getLabel(382323, '两栏视图')}
                >
                  <COMP
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_COMP@c1dobg@field`}
                    className={`icon br-none ${type == 'field' ? 'cur' : ''}`}
                    func={this.changeType}
                    type="field"
                  >
                    <i className={'icon-coms-Column icon-coms-Column-size'} />
                  </COMP>
                </Tooltip>
                <Tooltip
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Tooltip@ntamkn@${type}`}
                  title={getLabel(82532, '列表视图')}
                >
                  <COMP
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_COMP@s304vz@list`}
                    className={`icon bl-none ${type == 'list' ? 'cur' : ''}`}
                    func={this.changeType}
                    type="list"
                  >
                    <i className={'icon-coms-List'} />
                  </COMP>
                </Tooltip>
              </span>,
            ]}
            showDropIcon={Array.isArray(dropList) && dropList.length > 0}
            dropMenuDatas={dropList}
            onDropMenuClick={this.onDropMenuClick}
          >
            <div className="h100" style={{ position: 'relative' }}>
              <Spin
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Spin@hv7dm5`}
                spinning={leftList.params.layout * 1 === 0}
                className="cowork-view-loading"
                size="large"
              />
              <WeaLeftRightLayout
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaLeftRightLayout@2kije1`}
                isNew={true}
                showLeft={false}
                leftCom={
                  <CoworkTree
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_CoworkTree@0yxqjs`}
                  />
                }
              >
                {leftList.params.layout * 1 === 1 && (
                  <CoworkField
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_CoworkField@olv7qn`}
                    params={this.props.params}
                    currentKey={this.props.location}
                  />
                )}
                {leftList.params.layout * 1 === 2 && (
                  <CoworkTable
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_CoworkTable@yre4gc`}
                  />
                )}
              </WeaLeftRightLayout>
            </div>
          </WeaTop>
        </WeaRightMenu>
        <NewCowork
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_NewCowork@pycla2`}
          storeMapKey={storeMapKey}
        />
        <CoworkTagDialog
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_CoworkTagDialog@1v0cw7`}
        />
        {coworkMainStore.loaded &&
          window.weaCoworkEngine &&
          window.weaCoworkEngine.com &&
          window.weaCoworkEngine.com.PlateSetDialog && (
            <PlateSetDialog
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_PlateSetDialog@jmxleg`}
              isModal
              storeMapKey={coworkEnginePlateKey}
            />
          )}
        {coworkMainStore.loaded &&
          window.weaCoworkEngine &&
          window.weaCoworkEngine.com &&
          window.weaCoworkEngine.com.CategorySetDialog && (
            <CategorySetDialog
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_CategorySetDialog@2nq3u9`}
              isModal
              storeMapKey={coworkEngineCategoryKey}
            />
          )}
        <WeaLogViewComp
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaLogViewComp@3ddd4d`}
          visible={this.state.showLog}
          onCancel={this.onLogViewCancel}
          logStore={logStore}
          logType={logType}
          logSmallType={logSmallType}
          targetId={this.state.targetId}
        />
      </div>
    );
  }
}

export default Main;
